﻿Imports System
Imports System.Web
Imports System.Net
Imports System.IO
Imports NEvoWeb.Modules.NB_Store.SharedFunctions
Imports System.Collections.Specialized

Namespace NEvoWeb.Modules.NB_Store.Gateway

    Public Class GatewayEpay
        Inherits GatewayInterface

        Public Overrides Function GetButtonHtml(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String) As String
            Dim strHTML As String = ""
            Dim objSCtrl As New SettingsController
            Dim objSInfo As NB_Store_SettingsInfo

            'get the gateway settings from the NB_Store settings table
            objSInfo = objSCtrl.GetSetting(PortalID, "Epay.gateway", Lang)

            If Not objSInfo Is Nothing Then
                'Move the xml format settings into the a hashtable so we can use it easily.
                Dim setParams As Hashtable = createSettingsTable(objSInfo.SettingValue)

                'Build Html to display the payment button.
                strHTML = "<INPUT TYPE=IMAGE NAME=EPAYGATEWAY BORDER=0 SRC=""" & setParams("ButtonImageUrl") & """/>"

            End If

            Return strHTML
        End Function

        ' ------------------------------------------------------------------------
        ' Step Three: Auto Response from banking gateway.
        ' If the banking gateway supports Automatic response (A url is send to the store just after the users make the payment,
        ' but before they click to return to the store) then this function deals with what needs to be done in NB_Store.
        ' NOTE:
        ' - All parameters for the gateway are assigned by reading the gateway xml settings (In this case "PayPal.gateway")
        ' - Not all gateways support this, in which case the payment processing for NB_Store needs to be done in the "GetCompletedHtml" function.
        ' ------------------------------------------------------------------------

        Public Overrides Sub AutoResponse(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest)
            Try

                Dim objSCtrl As New SettingsController
                Dim objOCtrl As New OrderController
                Dim objPCtrl As New ProductController
                Dim objOInfo As NB_Store_OrdersInfo

                ' ------------------------------------------------------------------------
                ' In this case the payment provider passes back data via form POST.
                ' Get the data we need.
                Dim EpayStoreOrderID As Integer = CInt(Request.Form("orderid"))
                Dim EpayCartID As String = Request.Form("cartid")
                Dim EpayLang As String = Request.Form("lang")

                Dim OrdId = Request.QueryString("ordID")


                ' ------------------------------------------------------------------------

                'Log response data so we can tell if the auto response has worked.
                UpdateLog("AUTO = OrderID:" & EpayStoreOrderID & " ordID : " & OrdId & " CartId : " & EpayCartID & " Lang : " & EpayLang)

                'clear cart parameters, this is not strictly needed but does help tidy things up.
                Dim objCCtrl As New CartController
                Dim objCInfo As NB_Store_CartInfo = objCCtrl.GetCart(EpayCartID)
                If Not objCInfo Is Nothing Then
                    objCInfo.BankTransID = -1
                    objCInfo.BankHtmlRedirect = ""
                    objCCtrl.UpdateObjCart(objCInfo)
                End If

                ' ------------------------------------------------------------------------
                ' This section updates the order.
                objOInfo = objOCtrl.GetOrder(OrdId)
                If Not objOInfo Is Nothing Then
                    ' check if order has already been processed
                    If Not objOInfo.OrderIsPlaced Then
                        'remove qty in trans
                        objPCtrl.UpdateStockLevel(objOInfo.OrderID)
                        'set order status to Payed
                        objOInfo.OrderStatusID = 40
                        Dim UsrID As Integer = objOInfo.UserID
                        If UsrID = -1 Then UsrID = 0
                        objOInfo.OrderNumber = Format(PortalID, "00") & "-" & UsrID.ToString("0000#") & "-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
                        objOInfo.OrderIsPlaced = True
                        objOCtrl.UpdateObjOrder(objOInfo)

                        'Send email confirmation
                        SendEmailToClient(PortalID, GetClientEmail(PortalID, objOInfo), objOInfo.OrderNumber, objOInfo, "paymentOK.email", GetMerchantCulture(PortalID))
                        SendEmailToManager(PortalID, objOInfo.OrderNumber, objOInfo, "paymentOK.email")

                    End If
                End If
            Catch ex As Exception
                DotNetNuke.Services.Exceptions.LogException(ex) 'something went wrong, lets log the error...
                SendEmailToAdministrator(PortalID, "Epay AutoReturn ERROR", ex.ToString)
            End Try
        End Sub

        Public Overrides Function GetCompletedHtml(ByVal PortalID As Integer, ByVal UserID As Integer, ByVal Request As System.Web.HttpRequest) As String
            Dim rtnMsg As String = ""
            Dim objSCtrl As New SettingsController
            Dim objOCtrl As New OrderController
            Dim objPCtrl As New ProductController
            Dim objOInfo As NB_Store_OrdersInfo
            Dim objSInfo As NB_Store_SettingsTextInfo
            Dim ordID As Integer = -1

            'Get the order id back from the url.
            ordID = Request.QueryString("ordID")

            'set rtnMsg to security warning message.
            objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentSECURITY.text", GetCurrentCulture)
            rtnMsg = objSInfo.SettingText
            If IsNumeric(ordID) Then
                objOInfo = objOCtrl.GetOrder(ordID)
                If Not objOInfo Is Nothing Then
                    'Here we make sure that the user trying to view the order is the same as the user that placed the order.
                    'If this is not the case, then we want to display the security warning.
                    If objOInfo.UserID = UserID Then

                        'The user is OK, so continue to pocess the order.
                        '  In most circumstances the order will already have been processed by the Autoresponse function.
                        '  However it's always good practise to check this and process the order if it has not been done already.
                        '  If the payment provider does not support AutoResponse, then you must do the order processing here.

                        Select Case UCase(Request.QueryString("EpayExit"))
                            Case "CANCEL"
                                ' check if order has already been processed
                                If Not objOInfo.OrderIsPlaced Then
                                    'check if order has already been cancelled
                                    If Not objOInfo.OrderStatusID = 30 Then
                                        'remove qty in trans
                                        objPCtrl.RemoveModelQtyTrans(objOInfo.OrderID)
                                        'set order status to cancelled
                                        objOInfo.OrderStatusID = 30
                                        objOCtrl.UpdateObjOrder(objOInfo)
                                    End If
                                    'set Cancel order message
                                    objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentFAIL.text", GetCurrentCulture)
                                    rtnMsg = objSInfo.SettingText

                                End If
                            Case "RETURN"
                                ' check if order has already been processed
                                If Not objOInfo.OrderIsPlaced Then
                                    'remove qty in trans
                                    objPCtrl.UpdateStockLevel(objOInfo.OrderID)
                                    'set order status to Payed
                                    objOInfo.OrderStatusID = 45
                                    objOInfo.OrderNumber = Format(PortalID, "00") & "-" & UserID.ToString("0000#") & "-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
                                    objOInfo.OrderIsPlaced = True
                                    objOCtrl.UpdateObjOrder(objOInfo)
                                    'because in this case the order should have been processed by the autoresponse, but has not.
                                    'We're therefore going to send a payment unverified email to the client and manager.
                                    'This just tells the manager to check the payment has actually gone through.
                                    SendEmailToManager(PortalID, objOInfo.OrderNumber, objOInfo, "paymentunverified.email")
                                End If
                                'set completed order message
                                objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentOK.text", GetCurrentCulture)
                                rtnMsg = objSInfo.SettingText

                            Case Else
                                ' break
                        End Select

                        'Do Token Replacement
                        Dim objTR As New TokenStoreReplace(objOInfo, GetMerchantCulture(PortalID))
                        rtnMsg = objTR.DoTokenReplace(rtnMsg)
                    End If
                End If
            End If
            Return rtnMsg
        End Function

        Public Overrides Function GetBankClick(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest) As Boolean
            'test if button has been clicked
            If Not Request.Form.Item("EPAYGATEWAY.x") Is Nothing Then
                Return True
            Else
                Return False
            End If
        End Function

        Public Overrides Sub SetBankRemotePost(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String, ByVal Request As System.Web.HttpRequest)
            Dim RPost As New RemotePost ' RemotePost class from NB_Store, this generates the re-direct html required.

            'test if Epay button has been clicked
            If GetBankClick(PortalID, Request) Then
                'Get the gateway settings from the store setting Database
                Dim GatewayParams As String = GetStoreSetting(PortalID, "Epay.gateway", "None")
                If GatewayParams <> "" Then

                    'Parse the gateway setttings into a Hashtable for easy access.
                    Dim setParams As Hashtable = createSettingsTable(GatewayParams)

                    '-------------------------------------------------
                    'Get the basic required data from the settings.
                    ' with the exception of the ReturnNotifyUrl, these parameters are usually always required, by a payment provider
                    ' Obviously they may have different names depending on the provider.
                    Dim returnUrl As String = setParams("ReturnUrl")  ' Url that the payment provider will return the client to.
                    Dim cancelUrl As String = setParams("ReturnCancelUrl") ' Url to return the client if the payment failed.
                    Dim EpayUrl As String = setParams("paymentUrl") ' Url of the payment provider, where the client will be redirected so they can pay.
                    Dim notifyUrl As String = setParams("ReturnNotifyUrl") ' Url of the Auto Response, to update the order data in the store.
                    Dim MerchantNumber As String = setParams("MerchantNumber") 'ID  of the merchant who the payment is for.
                    Dim WindowState As String = setParams("WindowState") 'ID  of the merchant who the payment is for.
                    '-------------------------------------------------

                    '-------------------------------------------------
                    'Get any other needed parameters.
                    'These requirement of these parameters may differ, depending on the payment provider.
                    Dim EpayCartName As String = setParams("CartName")
                    Dim EpayButtonUrl As String = setParams("ButtonImageUrl")
                    Dim EpayCurrency As String = setParams("Currency")
                    Dim EpayLanguage As String = GetCurrentCulture()
                    'Dim SiteTitle As String = setParams("SiteTitle")
                    '-------------------------------------------------

                    'Get the order we want to pay for.
                    Dim objOCtrl As New OrderController
                    Dim oInfo As NB_Store_OrdersInfo = objOCtrl.GetOrder(OrderID)
                    If Not oInfo Is Nothing Then
                        '-------------------------------------------------
                        'The Url taken from the settings have tokens included for certain values.
                        'We need to replace these tokens with the actual values from the order.
                        returnUrl = Replace(returnUrl, "[ORDERID]", oInfo.OrderID.ToString)
                        cancelUrl = Replace(cancelUrl, "[ORDERID]", oInfo.OrderID.ToString)
                        notifyUrl = Replace(notifyUrl, "[ORDERID]", oInfo.OrderID.ToString)
                        '-------------------------------------------------
                        returnUrl = Replace(returnUrl, "[CARTID]", CurrentCart.GetCurrentCart(PortalID).CartID)
                        notifyUrl = Replace(notifyUrl, "[CARTID]", CurrentCart.GetCurrentCart(PortalID).CartID)
                        '-------------------------------------------------'-------------------------------------------------
                        returnUrl = Replace(returnUrl, "[LANG]", GetCurrentCulture())
                        notifyUrl = Replace(notifyUrl, "[LANG]", GetCurrentCulture())


                        'update stock transaction in progress
                        Dim objPCtrl As New ProductController
                        objPCtrl.UpdateModelQtyTrans(oInfo.OrderID)

                        'set order status to redirect to bank
                        oInfo.OrderStatusID = 20
                        objOCtrl.UpdateObjOrder(oInfo)

                        'get the gateway processing image we're going to display while connecting to the payment provider.
                        Dim gatewayImg As String = GetStoreSetting(PortalID, "gateway.loadimage", "None")

                        'Now assign the values we need to the RemotePost class, ready to build the re-direct html.
                        RPost = New RemotePost
                        RPost.Url = EpayUrl

                        RPost.Add("merchantnumber", MerchantNumber)
                        'reformmatting of the amounts may be required, depending on language settings and the needs of the provider.
                        RPost.Add("amount", HTTPPOSTEncode(Replace(Replace(oInfo.Total.ToString("0.00"), ".", ""), ",", "")))
                        RPost.Add("currency", EpayCurrency)
                        RPost.Add("windowstate", WindowState)
                        RPost.Add("accepturl", returnUrl)
                        RPost.Add("cancelurl", cancelUrl)
                        RPost.Add("callbackurl", notifyUrl)
                        RPost.Add("orderid", oInfo.OrderID.ToString)
                        RPost.Add("language", "0")


                        '-------------------------------------------------
                        'We are now going to save the re-direct html into the cart data on the database.
                        '  This is because the actual re-direct is done by the checkout module, when it loads.

                        'Get the cart data from the database.
                        Dim objCInfo As NB_Store_CartInfo = CurrentCart.GetCurrentCart(PortalID)
                        'Build and assign the re-direct html to the cart.
                        objCInfo.BankHtmlRedirect = RPost.GetPostHtml(gatewayImg)
                        'Save this data on the cart.
                        CurrentCart.Save(objCInfo)
                        '-------------------------------------------------

                        'Do a log statement of the html created, so we have a trace of what data has been passed. 
                        UpdateLog("Epay HTML = " & objCInfo.BankHtmlRedirect)

                    End If
                End If
            End If
        End Sub

        Public Function createSettingsTable(ByVal SettingsParams As String) As Hashtable
            Return ParseGateway(SettingsParams)
        End Function
    End Class


End Namespace
